
function setCookie(name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape(value) +
            ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) +
            ((path === null) ? "" : ("; path=" + path)) +
            ((domain === null) ? "" : ("; domain=" + domain)) +
            ((secure === true) ? "; secure" : "");
}
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr === -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) === arg)
            return getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i === 0)
            break;
    }
    return null;
}
function paint_array() {
    var arrayLignes = document.getElementById("car_rental").rows;
    var longueur = arrayLignes.length;
    var i = 0;
    while (i < longueur) {
        if (i % 2 === 0) {
            arrayLignes[i].style.backgroundColor = "#bdcbf5";
        } else {
            arrayLignes[i].style.backgroundColor = "#829eeb";
        }
        i++;
    }
    var arrayLignes2 = document.getElementById("hotel_reserv").rows;
    var longueur2 = arrayLignes2.length;
    var j = 0;
    while (j < longueur2) {
        if (j % 2 === 0) {
            arrayLignes2[j].style.backgroundColor = "#bdcbf5";
        } else {
            arrayLignes2[j].style.backgroundColor = "#829eeb";
        }
        j++;
    }
    var arrayLignes3 = document.getElementById("food_reserv").rows;
    var longueur3 = arrayLignes3.length;
    var k = 0;
    while (k < longueur3) {
        if (k % 2 === 0) {
            arrayLignes3[k].style.backgroundColor = "#bdcbf5";
        } else {
            arrayLignes3[k].style.backgroundColor = "#829eeb";
        }
        k++;
    }
}

function addToTotalAmount(price) {
    var total_price = parseFloat(getCookie("total_price"));
    if (isNaN(total_price)) {
        total_price = 0;
    }
    total_price += price;
    setCookie("total_price", total_price.toFixed(2));
}

function placeMarkerOnMap(place, descr) {
    var desc = descr;
    var addr = place;
    geocoder.geocode({'address': addr}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: addr});
            google.maps.event.addListener(marker, 'click', function() {
                window.alert(desc);
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}
function summarize(place, descr, contact, price) {
    document.getElementById("total_price").innerHTML = getCookie("total_price");
    var li = document.createElement('li');
    li.innerHTML = place + ': ' + descr + ' [' + contact + '] --- $' + price;
    document.getElementById("booked_services").appendChild(li);
}
function book_service(service_type, row_index) {
    var array_rows;
    if (service_type === "car") {
        array_rows = document.getElementById("car_rental").rows;
    } else if (service_type === "food") {
        array_rows = document.getElementById("food_reserv").rows;
    } else if (service_type === "hotel") {
        array_rows = document.getElementById("hotel_reserv").rows;
    }
    var service_row = array_rows[row_index].cells;
    var price = parseFloat(service_row[4].innerHTML.substring(1, service_row[4].innerHTML.length));
    var contact = service_row[3].innerHTML;
    var descr = service_row[2].innerHTML;
    var place = service_row[1].innerHTML;
    addToTotalAmount(price);
    placeMarkerOnMap(place, descr);
    summarize(place, descr, contact, price);
    array_rows[row_index].style.visibility = "hidden";
}

function trace_itinerary(departure, arrival) {
    var sAddr = departure;
    var dAddr = arrival;
    var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, panel: document.getElementById("trip_route")});
    var directionsService = new google.maps.DirectionsService();
    directionsService.route({ origin: sAddr, destination: dAddr, travelMode: google.maps.TravelMode.DRIVING}, function(results, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(results);
        } else {
            alert('Direction service was not successful for the following reason: ' + status);
        }
    });
}

function trace_route() {
    var date = document.getElementById("departure_date").value;
    setCookie("departure_date", date);
    var departure = document.getElementById("departure_addr").value;
    var arrival = document.getElementById("arrival_addr").value;
    trace_itinerary(departure, arrival);
}

var map;

var geocoder; // Exemple : variable déclarée dans le scope de Global

function initialize_map() {
    geocoder = new google.maps.Geocoder(); // geocoder n'a pas été déclaré dans ce scope alors javascript remonte la scope chain 
    					   // qui mène 1 cran plus haut à Global et retrouve la variable geocoder déclarée au dessus
    var latlng = new google.maps.LatLng(46.779231, 6.659431);
    var myoptions = {zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    map = new google.maps.Map(document.getElementById("road_map"), myoptions);
}

var xhr = new XMLHttpRequest();
var url = "http://localhost/planmytrip/leave_comment_servlet.php";
var leave_comment_callback = function() {
    if (xhr.readyState === 4) {/* request complete */
        if (xhr.status === 200) { /* HTTP return code 200 : OK */
            var res = this.responseText; // Ici on utilise this pour référencer l'objet courrant qui execute la méthode et qui est l'objet xhr créé à la ligne 155
            // pour l'utilsation exotique du mot clé this, c'est à dire le cas ou on utilise this dans une fonction qu'on l'appelle avec
            // le mot clé new, comme on a pas fait de new d'une fonction qu'on a définie nous meme on peut pas voir
            // la différence de l'utilisation du mot clé this entre les langages à classes et les langages à prototypes
            if (res === "OK") {
                location.reload();
            }
        }
    }
};
function leave_comment() {
    var msg = document.getElementById("comment").value;
    if (msg !== "") {
        xhr.open("POST", url, true);
        xhr.onreadystatechange = leave_comment_callback;
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send("comment=" + msg);
    } else {
        alert('Please pleave a message before');
    }
}

function load() { /* loaded when page is loaded */
    paint_array();
    initialize_map();
    document.getElementById("route_btn").addEventListener("click", trace_route, false);
    document.getElementById("comment_btn").addEventListener("click", leave_comment, false);
    var fileInput = document.getElementById("image_file"),
            progress = document.getElementById("progress");
    fileInput.onchange = function() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost/planmytrip/upload_picture_servlet.php');
        xhr.upload.onprogress = function(e) {
            progress.value = e.loaded;
            progress.max = e.total;
        };
        xhr.onload = function() {
            alert('Upload finished!');
        };
        var form = new FormData();
        form.append('image_file', fileInput.files[0]);
        xhr.send(form);
    };



    var xhr2 = new XMLHttpRequest();
    var url2 = "http://localhost/planmytrip/upload_picture_servlet.php";
    var upload_picture_callback = function() {
        if (xhr2.readyState === 4) {
            if (xhr2.status === 200) {
                var res = this.responseText;
                if (res === "OK") {
                    alert('File uploaded succesfully');
                }
            }
        }
    };
    function upload_picture() {
        xhr2.open("POST", url2, true);
        xhr2.onreadystatechange = upload_picture_callback;
        xhr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr2.send(null);
    }
}

google.maps.event.addDomListener(window, 'load', load);
